<template>
  <div class="login-bg">
    <div class="login-card">
      <h2 class="login-title">用户登录</h2>
      <el-form :model="loginForm" :rules="rules" ref="loginForm" class="login-form" @submit.native.prevent="handleLogin">
        <el-form-item prop="studentId">
          <el-input v-model="loginForm.studentId" placeholder="学号/手机号" prefix-icon="el-icon-user" />
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="loginForm.password" placeholder="密码" prefix-icon="el-icon-lock" show-password />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" style="width:100%;font-size:18px;" @click="handleLogin">登录</el-button>
        </el-form-item>
      </el-form>
      <div class="login-footer">
        没有账号？<a href="#" style="color:#409EFF;" @click.prevent="$router.push('/register')">去注册</a>
      </div>
    </div>
  </div>
</template>

<script>
import UserService from '@/Services/UserService'
import LogService from '@/Services/LogService'

export default {
  name: 'LoginView',
  data() {
    return {
      loginForm: {
        studentId: '',
        password: ''
      },
      rules: {
        studentId: [
          { required: true, message: '请输入学号或手机号', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    handleLogin() {
      this.$refs.loginForm.validate()
        .then(valid => {
          if (!valid) {
            return Promise.reject(new Error('表单验证失败'));
          }
          
          console.log('开始登录请求...');
          return UserService.Login(this.loginForm);
        })
        .then(async res => {
          console.log('登录响应:', res);
          
          if (!(res.code === 200)) {
            return Promise.reject(new Error(res.message || '登录失败'));
          }

          // 存储token
          const token = res.data;
          localStorage.setItem('token', token);
          localStorage.setItem('isLogged', 'true');
          
          console.log('存储的token:', localStorage.getItem('token'));
          console.log('登录状态:', localStorage.getItem('isLogged'));

          // 日志记录
          try {
            const userId = this.getCurrentUserId();
            await LogService.Create({
              id: this.generateGuid(),
              userId: userId,
              detail: `${this.loginForm.studentId}登陆成功`,
              createTime: new Date().toISOString()
            });
          } catch (logError) {
            console.error('记录登录日志失败：', logError);
          }

          this.$message.success('登录成功！');
          
          // 路由跳转
          console.log('准备跳转到HomeRegister...yuanxm');
          return this.$router.push({
            name: 'HomeRegister',
            replace: true
          });
        })
        .catch(error => {
          console.error('操作失败：', error);
          if (error.response) {
            console.error('错误响应:', error.response);
            this.$message.error(error.response.data.message || '登录失败，请稍后重试');
          } else {
            this.$message.error(error.message || '登录失败，请稍后重试');
          }
        });
    },

    // 获取当前用户ID，模仿PublishView.vue
    getCurrentUserId() {
      const token = localStorage.getItem('token')
      if (!token) return null
      try {
        const base64Url = token.split('.')[1]
        const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/')
        const jsonPayload = decodeURIComponent(atob(base64).split('').map(c => {
          return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)
        }).join(''))
        const payload = JSON.parse(jsonPayload)
        // 兼容多种常见字段
        return payload.userId || payload.sub || payload.id || payload.nameid || payload["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier"]
      } catch (error) {
        console.error('解析token失败：', error)
        return null
      }
    },

    // 生成GUID的方法
    generateGuid() {
      return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        const r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8)
        return v.toString(16)
      })
    }
  }
}
</script>

<style scoped>
.login-bg {
  min-height: 100vh;
  background: linear-gradient(135deg, #fffbe6 0%, #ffe100 100%);
  display: flex;
  align-items: center;
  justify-content: center;
}
.login-card {
  background: #fff;
  border-radius: 18px;
  box-shadow: 0 4px 24px 0 rgba(0,0,0,0.10);
  padding: 48px 40px 32px 40px;
  width: 360px;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.login-title {
  font-size: 28px;
  color: #222;
  margin-bottom: 32px;
  font-weight: bold;
  letter-spacing: 2px;
}
.login-form {
  width: 100%;
}
.login-footer {
  margin-top: 18px;
  color: #888;
  font-size: 15px;
  text-align: center;
}
</style> 